package org.feng.config;

import lombok.extern.slf4j.Slf4j;
import org.feng.api.ResultVo;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Iterator;
import java.util.Set;

import static org.springframework.http.HttpStatus.OK;

/**
 * 全局异常处理
 *
 * @author feng
 */
@Slf4j
@RestControllerAdvice
public class ExceptionInterceptor {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(OK)
    ResultVo<String> handleRootException(Exception ex) {
        log.error("Unknown Error ! ", ex);
        return new ResultVo<>(500, ex.getMessage(), null);
    }


    /**
     * 违反约束，javax扩展定义与自定义校验
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(OK)
    ResultVo<String> handleConstraintViolationException(ConstraintViolationException exception) {
        log.warn("handleConstraintViolationException occurred ! ", exception);
        Set<ConstraintViolation<?>> constraintViolations = exception.getConstraintViolations();
        Iterator<ConstraintViolation<?>> iterator = constraintViolations.iterator();
        StringBuilder sBuffer = new StringBuilder();
        while (iterator.hasNext()) {
            sBuffer.append(" ").append(iterator.next().getMessage()).append(";");
        }
        return new ResultVo<>(500, sBuffer.toString(), null);
    }

    /**
     * 参数无效，如JSON请求参数违反约束
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(OK)
    ResultVo<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException exception) {
        log.warn("handleMethodArgumentNotValidException occurred ! ", exception);
        StringBuilder stringBuffer = new StringBuilder();
        for (FieldError error : exception.getBindingResult().getFieldErrors()) {
            stringBuffer.append(error.getDefaultMessage()).append(";");
        }
        return new ResultVo<>(500, stringBuffer.toString(), null);
    }
}
